<!--
 * @Description: 编辑会员等级
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2023-08-08 16:06:24
 * @LastEditTime: 2023-08-30 10:36:24
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
-->

<template>
  <div class="lb-custom-member-level-edit">
    <top-nav :title="navTitle" :isBack="true"></top-nav>
    <div class="page-main">
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="subForm"
        label-width="180px"
        class="basic-form"
      >
        <lb-classify-title title="基础信息"></lb-classify-title>
        <div style="height: 30px"></div>
        <div class="flex-warp">
          <div class="mr-lg">
            <el-form-item label="等级名称" prop="title">
              <el-input
                v-model="subForm.title"
                type="text"
                maxlength="6"
                show-word-limit
                placeholder="请输入会员等级名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="等级背景色" prop="color">
              <div class="flex-warp mt-sm">
                <div v-for="(item, index) in colorList" :key="index">
                  <div
                    @click="changeIndex(index)"
                    class="color-item"
                    :class="[{ active: index === colorInd }]"
                    v-if="index < colorList.length - 1"
                  >
                    <div class="flex-center">
                      <div class="primaryColor flex-center">
                        <div
                          class="color-bg"
                          :style="{ background: item }"
                        ></div>
                      </div>
                    </div>
                    <i
                      class="iconfont icon-xuanze-fill flex-center"
                      v-if="index === colorInd"
                    ></i>
                  </div>
                  <div v-if="index == colorList.length - 1">
                    <div
                      @click="changeIndex(index)"
                      class="color-item"
                      :class="[{ active: index === colorInd }]"
                      style="width: auto; padding: 0 2px"
                    >
                      <div class="flex-center" style="margin-top: 4px">
                        <el-color-picker
                          @change="changeColor"
                          size="mini"
                          style="margin-right: 4px"
                          v-model="colorList[index]"
                        ></el-color-picker>
                      </div>
                      <div
                        class="flex-y-center"
                        style="height: 18px; margin-top: 4px"
                      >
                        <div style="line-height: 18px; font-size: 10px">
                          自定义配色
                        </div>
                        <i
                          class="iconfont icongouxuan-weixuanzhong-xianxingyuankuang flex-center"
                          :class="[
                            {
                              'icon-xuanze-fill':
                                index === colorInd
                            }
                          ]"
                          style="margin: 0"
                        ></i>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="获得等级条件" prop="growth">
              <el-input
                :placeholder="last_level_growth"
                v-model.number="subForm.growth"
              >
                <template slot="prepend">成长值达到</template>
              </el-input>
              <lb-tool-tips
                >修改成长值会影响现有会员用户的会员等级，请谨慎操作</lb-tool-tips
              >
            </el-form-item>
          </div>

          <div class="ml-lg">
            <div class="swiper-item radius-26 rel">
              <div
                class="swiper-item has-shadow c-base radius-26"
                :style="{ background: subForm.color || primaryColor }"
              ></div>
              <div class="swiper-item abs" style="top: 0; left: 0">
                <div class="flex-between item-child">
                  <div style="width: 170px">
                    <div
                      class="flex-y-baseline mt-lg"
                      :style="{ color: subForm.color || primaryColor }"
                    >
                      <div class="vip-icon flex-center rel">
                        <i class="iconfont iconvIP1"></i>
                        <div class="f-desc flex-center c-base abs">v{{top}}</div>
                      </div>
                      <div class="f-sm-title text-bold ml-sm">
                        {{ subForm.title || '会员等级名称' }}
                      </div>
                    </div>
                    <div
                      class="f-icontext"
                      style="height: 15px"
                      :style="{ color: subForm.color || primaryColor }"
                    >
                      等级有效期: 长期有效
                    </div>
                    <div style="height: 22px"></div>
                    <div class="f-icontext ellipsis" style="color: #525252;height:17px">
                     <block v-if="subForm.id">
                       <block v-if="next_level && next_level.id">
                        还差{{ next_growth }}成长值升级至{{ next_level.title }}
                      </block>
                      <block v-else>已是最高会员等级</block>
                     </block>
                    </div>
                    <div
                      class="mb-sm line-bg rel radius"
                      style="margin-top: 8px"
                    >
                      <div
                        class="line-bg abs radius"
                        :style="{
                          width: `40%`,
                          background: subForm.color || primaryColor
                        }"
                      ></div>
                    </div>
                    <div class="f-desc text-bold" style="color: #525252">
                      {{ cur_growth }}/{{ total_growth}}
                    </div>
                  </div>
                  <img
                    class="member-img"
                    src="https://lbqny.migugu.com/admin/anmo/member/member.png"
                  >
                  </img>
                </div>
              </div>
            </div>
            <lb-tool-tips mode="text"
              ><div class="c-warning">
                仅为模拟效果，实际以显示效果为准
              </div></lb-tool-tips
            >
          </div>
        </div>
        <div style="height: 30px"></div>
        <lb-classify-title title="权益信息"></lb-classify-title>
        <div style="height: 30px"></div>
        <el-form-item label="会员权益" prop="rights">
          <el-checkbox-group v-model="subForm.rights">
            <div
              class="c-title"
              style="height: 30px"
              v-for="(item, index) in base_rights"
              :key="index"
              v-show="item.key !== 'send_coupon'"
            >
              <el-checkbox :label="item.id">{{ item.title }}</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="升级礼包" prop="coupon" v-if="send_coupon_id">
          <el-checkbox-group v-model="subForm.rights">
            <div
              class="c-title"
              style="height: 30px"
              v-for="(item, index) in base_rights"
              :key="index"
              v-show="item.key === 'send_coupon'"
            >
              <el-checkbox :label="item.id">{{ item.title }}</el-checkbox>
              <lb-button
                type="danger"
                size="small"
                class="ml-md"
                icon="el-icon-plus"
                @click="toShowDialog('coupon')"
                v-if="send_coupon_id && subForm.rights.includes(send_coupon_id)"
                >选择卡券</lb-button
              >
            </div>
          </el-checkbox-group>
          <div
            class="mt-lg pt-sm"
            v-if="send_coupon_id && subForm.rights.includes(send_coupon_id)"
          >
            <el-table
              :data="subForm.coupon"
              :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
              style="width: 600px"
            >
              <el-table-column
                prop="title"
                label="优惠券名称"
              ></el-table-column>
              <el-table-column prop="num" label="数量" width="220">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.num"
                    :precision="0"
                    :min="1"
                    :max="1000"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template slot-scope="scope">
                  <div class="table-operate">
                    <lb-button
                      size="mini"
                      plain
                      type="danger"
                      @click="confirmDel(scope.row.id)"
                      >{{ $t('action.delete') }}</lb-button
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <div style="height: 30px"></div>
        <el-form-item>
          <lb-button type="primary" @click="submitFormInfo" v-preventReClick>{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="$router.back(-1)">{{
            $t('action.back')
          }}</lb-button>
        </el-form-item>
      </el-form>

      <el-dialog
        title="选择卡券"
        :visible.sync="showDialog.coupon"
        width="900px"
        center
      >
        <el-form
          :inline="true"
          :model="searchForm"
          ref="searchForm"
          label-width="70px"
          class="dialog-form"
        >
          <el-form-item label="输入查询" prop="name">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入卡券名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1)"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('searchForm')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
        <el-table
          :data="tableData"
          ref="multipleTable"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="title" label="卡券名称"></el-table-column>
          <el-table-column prop="type" label="使用条件">
            <template slot-scope="scope">
              <p>
                {{
                  scope.row.type === 0
                    ? `消费满¥${scope.row.full}减¥${scope.row.discount}`
                    : `立减¥${scope.row.discount}`
                }}
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="数量" width="260">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.num"
                @change="handleChange"
                :precision="0"
                :min="1"
                :max="1000"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
        <lb-page
          :batch="false"
          :page="searchForm.page"
          :pageSize="searchForm.limit"
          :total="total"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        >
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.coupon = false">取 消</el-button>
          <el-button
            type="primary"
            @click="handleDialogConfirm"
            v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    let checkCoupon = (rule, value, callback) => {
      let { rights } = this.subForm
      let { send_coupon_id: id } = this
      if (rule.key === 'rights' && ((!rights.includes(id) && value.length === 0) || ((rights.includes(id) && value.length === 1)))) {
        callback(new Error(`请选择会员权益`))
      } else if (rule.key === 'send_coupon' && rights.includes(id) && value.length === 0) {
        callback(new Error(`请选择卡券`))
      } else {
        callback()
      }
    }
    return {
      navTitle: '',
      colorList: [
        '#739bc6',
        '#60a06a',
        '#d4b64c',
        '#c09e51',
        '#d5964b',
        '#c26a51',
        '#ffb6b1',
        '#b0b4c7',
        '#616570',
        '#616570'
      ],
      colorInd: 0,
      primaryColor: '#739bc6',
      base_rights: [],
      top: '',
      cur_growth: '40',
      total_growth: '100',
      next_level: {},
      send_coupon_id: 0,
      subForm: {
        id: '',
        title: '',
        color: '#739bc6',
        growth: '',
        rights: [],
        coupon: []
      },
      subFormRules: {
        title: { required: true, validator: this.$reg.isNotNull, reg_type: 2, text: '会员等级名称', trigger: 'blur' },
        color: { required: true, type: 'string', message: '请选择背景色', trigger: 'blur' },
        growth: { required: true, validator: this.$reg.isNum, text: '成长值', trigger: 'blur' },
        rights: { required: true, validator: checkCoupon, key: 'rights', trigger: ['blur', 'change'] },
        coupon: { validator: checkCoupon, key: 'send_coupon', trigger: ['blur', 'change'] }
      },
      searchForm: {
        page: 1,
        limit: 10,
        status: 1,
        send_type: 3,
        name: ''
      },
      total: 0,
      loading: false,
      tableData: [],
      multipleSelection: [],
      showDialog: { coupon: false },
      selectable (row, index) {
        if (row.number > 0) {
          return true
        } else {
          return false
        }
      }
    }
  },
  async created () {
    let { id = 0, top = 1 } = this.$route.query
    this.navTitle = this.$t(id ? 'menu.CustomMemberLevelEdit' : 'menu.CustomMemberLevelAdd')
    this.subForm.id = id
    this.top = top
    await this.getBaseInfo()
    if (id) {
      await this.getDetail()
    }
  },
  methods: {
    async getBaseInfo () {
      let { code, data } = await this.$api.member.rightsSelect()
      if (code !== 200) return
      let ind = data.findIndex(item => {
        return item.key === 'send_coupon'
      })
      this.send_coupon_id = ind === -1 ? 0 : data[ind].id
      this.base_rights = data
    },
    async getDetail () {
      let { id } = this.subForm
      this.subForm.color = this.colorList[this.colorInd]
      let { code, data } = await this.$api.member.levelInfo({ id })
      if (code !== 200) return
      if (!data.color || data.color === '0') {
        data.color = this.colorList[0]
      }
      let ind = -1
      this.colorList.map((item, index) => {
        if (item === data.color) {
          ind = index
        }
      })
      this.colorInd = ind === -1 && data.color ? this.colorList.length - 1 : ind
      if (ind === -1 && data.color) {
        this.colorList[this.colorList.length - 1] = data.color
      }
      data.coupon = data.coupon.map(item => {
        let { coupon_id: cid, title, num } = item
        return { id: cid, title, num }
      })
      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
      let { next_level: next = { id: 0, growth: 0 } } = data
      next = next == null ? { id: 0, growth: 0 } : next
      let { id: nid = 0, growth = 0 } = next
      let total = nid ? growth * 1 : data.growth * 1
      let cur = total * 0.4
      this.cur_growth = cur
      this.total_growth = total
      this.next_level = data.next_level
    },
    async changeIndex (index) {
      this.colorInd = index
      this.subForm.color = this.colorList[index]
    },
    changeColor (e) {
      this.subForm.color = e
    },
    async toShowDialog (key) {
      this.searchForm.page = 1
      this.searchForm.name = ''
      await this.getTableDataList()
      this.showDialog[key] = !this.showDialog[key]
    },
    resetForm (form) {
      this.$refs[form].resetFields()
      this.getTableDataList(1)
    },
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.getTableDataList()
    },
    async getTableDataList (flag) {
      if (flag) this.searchForm.page = 1
      this.loading = true
      let { code, data } = await this.$api.market.couponList(this.searchForm)
      this.loading = false
      if (code !== 200) return
      let { coupon } = this.subForm
      let arr = coupon.map(item => {
        return item.id
      })
      data.data.map(item => {
        item.num = 1
        if (arr.includes(item.id)) {
          let ind = coupon.findIndex(aitem => {
            return item.id === aitem.id
          })
          item.num = coupon[ind].num
        }
      })
      this.tableData = data.data
      this.total = data.total
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    handleDialogConfirm () {
      if (this.multipleSelection.length === 0) {
        this.$message.error(`请选择卡券`)
        return
      }
      let coupon = JSON.parse(JSON.stringify(this.subForm.coupon))
      let arr1 = coupon.length > 0 ? coupon.map(item => { return item.id }) : []
      this.multipleSelection.map(item => {
        if (arr1.includes(item.id)) {
          let ind = coupon.findIndex(aitem => {
            return aitem.id === item.id
          })
          coupon[ind].num = item.num
        } else {
          coupon.push(item)
        }
      })
      this.subForm.coupon = coupon
      this.showDialog.coupon = false
    },
    confirmDel (id) {
      let index = this.subForm.coupon.findIndex(item => {
        return item.id === id
      })
      this.subForm.coupon.splice(index, 1)
    },
    async submitFormInfo () {
      let flag = true
      this.$refs['subForm'].validate(valid => {
        if (!valid) flag = false
      })
      if (flag) {
        let subForm = JSON.parse(JSON.stringify(this.subForm))
        let coupon = []
        subForm.coupon.map((item) => {
          coupon.push({ coupon_id: item.id, num: item.num || 0 })
        })
        subForm.coupon = subForm.rights.includes(this.send_coupon_id) ? coupon : []
        if (subForm.rights.includes(this.send_coupon_id) && subForm.coupon.filter(item => {
          return item.num * 1 < 1
        }).length > 0) {
          this.$message.error(`请输入卡券数量`)
          return
        }
        let methodModel = subForm.id ? 'levelUpdate' : 'levelAdd'
        let { code } = await this.$api.member[methodModel](subForm)
        if (code !== 200) return
        this.$message.success(this.$t('tips.successSub'))
        this.$router.back(-1)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-custom-member-level-edit {
  width: 100%;

  .el-input,
  .el-select,
  .lb-input-number,
  .el-cascader,
  .el-textarea {
    width: 400px;
  }

  .color-item {
    width: 40px;
    height: 58px;
    margin-right: 5px;
    padding-top: 4px;
    border: 1px solid white;
    cursor: pointer;
    .primaryColor {
      width: 28px;
      height: 28px;
      border-radius: 3px;
      border: 1px solid #e6e6e6;
      .color-bg {
        width: 20px;
        height: 20px;
        border-radius: 3px;
      }
    }
    .iconfont {
      color: #429dff;
      margin-top: 5px;
    }
  }
  .color-item.active {
    border: 1px solid #429dff;
    border-radius: 3px;
    box-shadow: 0px 4px 12px 1px rgba(66, 157, 255, 0.15);
  }

  .swiper-item {
    width: 320px;
    height: 180px;
    margin: 0 auto;

    .current-level {
      top: 0;
      left: 0;
      width: 70px;
      height: 20px;
      background: rgba(255, 255, 255, 0.5);
      box-shadow: 0 9px 11px 0 rgba(211, 213, 212, 0.29);
      border-radius: 13px 0 13px 0;
    }

    .item-child {
      height: 180px;
      padding: 0 12px 0 15px;

      .vip-icon {
        .iconvIP1 {
          font-size: 25px;
        }

        .abs {
          bottom: 0;
          left: 0;
          z-index: 1;
          width: 27px;
          height: 15px;
          transform: scale(0.8);
        }
      }

      .member-img {
        width: 115px;
        height: 115px;
      }

      .line-bg {
        width: 170px;
        height: 10px;
        background: rgba(255, 255, 255, 0.5);
      }

      .line-bg.abs {
        top: 0;
        left: 0;
      }
    }
  }
  .radius-26 {
    border-radius: 13px;
  }

  .has-shadow {
    opacity: 0.3;
    box-shadow: 0px 17px 23px 0px rgba(211, 213, 212, 0.29);
  }

  .has-scale {
    transform: scale(0.9);
  }

  .dialog-form {
    .el-input {
      width: 300px;
    }
  }
}
</style>
